<template>
  <van-list
    :immediate-check="false"
    v-model="loading"
    :finished="finished"
    finished-text="没有更多了"
    @load="onLoad"
  >
    <commentItem
      @reply-click="$emit('reply-click', $event)"
      v-for="comment in list"
      :key="comment.com_id"
      :comment="comment"
    ></commentItem>
    <!-- <van-cell
      v-for="item in list"
      :key="item.com_id"
      :title="item.content"
    ></van-cell> -->
  </van-list>
</template>
<script>
import { getComments } from '@/api/comment'
import commentItem from './comment-item.vue'
export default {
  name: 'CommentList',
  components: {
    commentItem
  },
  props: {
    list: {
      type: Array,
      default: () => []
    },
    source: {
      type: [String, Number],
      required: true
    },
    type: {
      type: String,
      default: 'a'
    }
  },
  data () {
    return {
      // list: [], // 评论列表
      loading: false, // 上拉加载更多的 loading
      finished: false, // 是否加载结束

      // type: "a", // a | c
      offset: null,
      limit: 10 // 每页评论数
    }
  },
  created () {
    // 手动触发的话 loading不会自动设置为true
    this.loading = true
    this.onLoad()
  },
  methods: {
    async onLoad () {
      try {
        const res = await getComments({
          type: this.type,
          source: this.source,
          offset: this.offset,
          limit: this.limit
        })
        this.$emit('commentCounts', res.data.data.total_count)
        const results = res.data.data.results
        this.list.push(...results)
        // 将 loading 设置为fales
        this.loading = false
        // 判断数据是否加载完毕
        if (results.length) {
          this.offset = res.data.data.last_id
        } else {
          this.finished = true
        }
        console.log(res)
      } catch (error) {
        console.log(error)
        this.loading = false
      }
    }
  }
}
</script>
